package com.alan.netty.rpc.v1;

import com.alan.netty.rpc.common.RpcRequest;
import com.alan.netty.rpc.common.RpcResponse;
import com.alan.netty.rpc.common.Serializer;
import com.alan.netty.rpc.common.handler.RpcDecode;
import com.alan.netty.rpc.common.handler.RpcEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;

/**
 * @author weiBin
 * @date 2018/11/27
 */
public class RpcClient {
    private Channel channel;
    /**
     * rpc通信结果集合
     */
    private static ConcurrentHashMap<String, SynchronousQueue<RpcResponse>> mapInfo = new ConcurrentHashMap<>();

    public static void putSynchronousQueue(String id, SynchronousQueue<RpcResponse> queue) {
        mapInfo.put(id, queue);
    }

    public static SynchronousQueue<RpcResponse> getSynchronousQueue(String id) {
        return mapInfo.get(id);
    }

    public static SynchronousQueue<RpcResponse> removeById(String id) {
        return mapInfo.remove(id);
    }

    /**
     * 初始化创建客户端socketChannel连接
     *
     * @param host
     * @param port
     * @param serializer
     */
    public void init(String host, int port, final Serializer serializer) {
        try {
            Bootstrap bootstrap = new Bootstrap();
            NioEventLoopGroup group = new NioEventLoopGroup();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(NioSocketChannel ch) throws Exception {
                      ChannelPipeline pipeline = ch.pipeline();
                      //rpcResponse解码
                      pipeline.addLast(new RpcDecode(RpcResponse.class, serializer));
                      //rpcRequest 编码
                      pipeline.addLast(new RpcEncode(RpcRequest.class, serializer));
                      //对 rpcResponse 业务处理
                      pipeline.addLast(new RpcClientHandler());
                  }
              }
            ).option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.SO_REUSEADDR, true);
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写rpcRequest报文
     *
     * @param rpcRequest
     */
    public void writeRpcRequest(RpcRequest rpcRequest) {
        try {
            this.channel.writeAndFlush(rpcRequest).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否活跃
     *
     * @return
     */
    public boolean isValidate() {
        if (null != channel) {
            return channel.isActive();
        }
        return false;
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (null != channel && channel.isOpen()) {
            channel.close();
        }
    }
}
